<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.1.0/socket.io.js"></script>
    <title>Document</title>
    <script>
        $(function () {
            var socket = io("/", {
                transports: ["websocket"]
            })
            socket.on("returnMsg", (data) => {
                var name = $('#username').text();
                // alert(JSON.stringify(data))
                if (name === data.username) {
                    $("#messageList").append(`<div class="right">${data.msg}:<strong>${data.username}</strong></div>`)
                } else {
                    $("#messageList").append(`<div class="left"><strong>${data.username}:</strong>${data.msg}</div>`)
                }
            })
            window.socket = socket;
        })
        function send() {
            const msg = $('#message').val();
            if (msg === '') {
                alert("发送不能为空!")
            } else {
                window.socket.emit('index', { msg });
                $('#message').val('');//文本框值清空
            }
        }
    </script>
</head>

<body>
    <div class="container">
        <h1><span id="username"><%=username%></span>,欢迎来到聊天室！</h1>
        <div id="messageList"></div>
        <div class="text">
            <textarea id="message"></textarea>
            <input type="button" value="发送" onclick="send()">
        </div>
    </div>
</body>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    .container h1 {
        height: 150px;
        background: #ccc;
        line-height: 150px;
        text-align: center;
    }

    .container h1 span {
        color: red;
    }

    #messageList {
        height: 400px;
        background: #e8e5e538;
        margin-bottom: 40px;
    }

    #messageList strong {
        color: red;
    }

    .right {
        width: 98%;
        height: 30px;
        text-align: right;
    }

    .left {
        width: 100%;
        height: 30px;
        padding-left: 20px;
    }

    .text {
        width: 700px;
        height: 120px;
        margin: 0 auto;
    }

    .text textarea {
        width: 600px;
        height: 100px;
        border-radius: 5px;
    }

    .text input {
        width: 50px;
        position: absolute;
        top: 630px;
        right: 28%;
    }
</style>

</html>